/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Zeshui Xu<i@xuzeshui.com>
 * Created Time: 2015-12-20 13:14:17
 * Last Modified: 2017-07-21 18:03:44
 * File Name: admin/passport.go
 * Description:
 */
package admin

import (
	"passport/account"
	"passport/invitecode"
	"passport/user"

	log "github.com/cihub/seelog"
)

var (
	passportAdmin *PassportAdmin
)

type PassportAdmin struct{}

/*
	根据userid删除账号系统中所有相关数据
*/
func (p *PassportAdmin) DeletePassportByUserid(userid string) error {
	//获取用户信息
	ui, errUi := user.GetUserService().GetAllUserInfo(userid)
	if errUi != nil {
		log.Warnf("GetAllUserInfo for userid: %s, error: %s", userid, errUi.Error())
		return errUi
	}
	if ui == nil {
		log.Warnf("GetAllUserInfo for userid: %s empty!", userid)
		return nil
	}

	//查询绑定账号信息,并删除所有绑定的账号
	if bindedAccounts, err := account.GetAccountBindService().GetBindedAccountForUserid(userid); err == nil {
		for extFrom, extId := range bindedAccounts {
			aichanger := account.NewAccountInfoChanger(extId, extFrom)
			aichanger.Delete()
			account.GetAccountBindService().RecordUserAccountUnbind(userid, extFrom)
		}
	}

	//删除邀请码账号
	invitecode.GetInviteCodeService().DeleteICAccount(ui.InviteCode)

	//删除该用户的邀请码好友纪录
	invitecode.GetInviteCodeService().ClearInviteCodeRegRecord(userid)

	//邀请码归还重新分配
	invitecode.GetInviteCodeService().GivebackInviteCode(ui.InviteCode)

	//让登录失效,清除登录token
	account.GetAccessTokenService().ExpireUserAccessToken(userid)

	//删除用户信息
	uichanger := user.NewUserInfoChanger(userid)
	uichanger.Delete()

	log.Warnf("DeletePassport Success For userid: %s", userid)

	return nil
}

func GetPassportAdmin() *PassportAdmin {
	return passportAdmin
}

func init() {
	passportAdmin = &PassportAdmin{}
}
